package com.hlf.modules.api.controller;

/**
 * Created by Administrator on 2017/9/28.
 */


import com.alibaba.fastjson.JSON;
import com.hlf.common.annotation.SysLog;
import com.hlf.common.constants.Constants;
import com.hlf.common.constants.FileConstants;
import com.hlf.common.exception.BusinessException;
import com.hlf.common.utils.FTPImageTask;
import com.hlf.common.utils.PropertieUtil;
import com.hlf.common.utils.ReturnResult;
import com.hlf.modules.sys.controller.AbstractController;
import com.hlf.modules.sys.entity.File;
import com.hlf.modules.sys.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件控制类
 */
@RestController
@RequestMapping("/api/file")
@Api("文件控制接口")
public class ApiFileController extends AbstractController{

    @Autowired
    private FileService fileService;
    @Autowired
    private FTPImageTask ftpImageTask;
    @Autowired
    private PropertieUtil propertieUtil;

    /**
     * 上传文件
     *
     * @param request
     * @param type    文件类型
     * @return
     * @throws IOException
     */
    @PostMapping("/{type}/uploadFile")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true),
            @ApiImplicitParam(paramType = "query", name = "type", value = "文件类型", required = true)
    })
    public ReturnResult uploadFile(HttpServletRequest request,
                                   @PathVariable("type") String type) throws IOException {
        // 文件类型
        String filType = "";
        // 文件类型名称
        String filTypeName = "";
        // 文件类型路径
        String typePath = "";
        switch (type) {
            case FileConstants.CORP_IMG:
                filType = FileConstants.CORP_IMG;
                filTypeName = FileConstants.CORP_IMG_NAME;
                typePath = FileConstants.CORP_IMG_PATH;
                break;
            case FileConstants.BUSINESS_IMG:
                filType = FileConstants.BUSINESS_IMG;
                filTypeName = FileConstants.BUSINESS_IMG_NAME;
                typePath = FileConstants.BUSINESS_IMG_PATH;
                break;
            case FileConstants.TAX_REG_CERTIF_IMG:
                filType = FileConstants.TAX_REG_CERTIF_IMG;
                filTypeName = FileConstants.TAX_REG_CERTIF_IMG_NAME;
                typePath = FileConstants.TAX_REG_CERTIF_PATH;
                break;
            case FileConstants.ORG_IMG:
                filType = FileConstants.ORG_IMG;
                filTypeName = FileConstants.ORG_IMG_NAME;
                typePath = FileConstants.ORG_IMG_PATH;
                break;
            case FileConstants.AGREEMENT_IMG:
                filType = FileConstants.AGREEMENT_IMG;
                filTypeName = FileConstants.AGREEMENT_IMG_NAME;
                typePath = FileConstants.AGREEMENT_IMG_PATH;
                break;
            case FileConstants.LOGO_IMG:
                filType = FileConstants.LOGO_IMG;
                filTypeName = FileConstants.LOGO_IMG_NAME;
                typePath = FileConstants.LOGO_IMG_PATH;
                break;
            case FileConstants.APK:
                filType = FileConstants.APK;
                filTypeName = FileConstants.APK_NAME;
                typePath = FileConstants.APK_PATH;
                break;
            case FileConstants.FEEDBACK_IMG:
                filType = FileConstants.FEEDBACK_IMG;
                filTypeName = FileConstants.FEEDBACK_NAME;
                typePath = FileConstants.FEEDBACK_PATH;
                break;
            case FileConstants.IDENTITY_CARD_IMG:
                filType = FileConstants.IDENTITY_CARD_IMG;
                filTypeName = FileConstants.IDENTITY_CARD_NAME;
                typePath = FileConstants.IDENTITY_CARD_PATH;
                break;
            case FileConstants.BANK_CARD_IMG:
                filType = FileConstants.BANK_CARD_IMG;
                filTypeName = FileConstants.BANK_CARD_NAME;
                typePath = FileConstants.BANK_CARD_PATH;
                break;
            case FileConstants.STORE_IMG:
                filType = FileConstants.STORE_IMG;
                filTypeName = FileConstants.STORE_NAME;
                typePath = FileConstants.STORE_PATH;
                break;
            case FileConstants.GOODS_IMG:
                filType = FileConstants.GOODS_IMG;
                filTypeName = FileConstants.GOODS_NAME;
                typePath = FileConstants.GOODS_PATH;
                break;
            case FileConstants.MERCHANT_IMG:
                filType = FileConstants.MERCHANT_IMG;
                filTypeName = FileConstants.MERCHANT_NAME;
                typePath = FileConstants.MERCHANT_PATH;
                break;
            case FileConstants.OPEN_ACCOUNT_LICENSE_IMG:
                filType = FileConstants.OPEN_ACCOUNT_LICENSE_IMG;
                filTypeName = FileConstants.OPEN_LICENSE_NAME;
                typePath = FileConstants.OPEN_LICENSE_PATH;
                break;
            case FileConstants.QS_IMG:
                filType = FileConstants.QS_IMG;
                filTypeName = FileConstants.QS_NAME;
                typePath = FileConstants.QS_PATH;
                break;
            case FileConstants.STORE_SIGN_IMG:
                filType = FileConstants.STORE_SIGN_IMG;
                filTypeName = FileConstants.STORE_SIGN_NAME;
                typePath = FileConstants.STORE_SIGN_PATH;
                break;
            default:
                throw new BusinessException("文件类型不正确");
        }
        List<File> fileList = fileService.uploadFile(request, filType, filTypeName, typePath);

        String s = JSON.toJSONString(fileList);

        return ReturnResult.ok().put(Constants.DEFAULT_RESULT_NAME,s);
    }

    /**
     * 删除文件
     *
     * @param request
     * @param
     */
    @SysLog("删除文件")
    @ResponseBody
    @PostMapping("deleteFile")
    @ApiOperation(value = "删除文件", notes = "删除文件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "token", value = "token", required = true),
            @ApiImplicitParam(paramType = "query", name = "fileIds", value = "文件id/批量", required = true)
    })
    public ReturnResult deleteFile(HttpServletRequest request, @RequestParam(value = "fileIds",required = false) List<Long> fileIds) {
        if (fileIds.size() == 0){
            logger.info("文件id为空!");
            throw new BusinessException("文件id不能为空!");
        }
        for (Long fileId : fileIds) {
            fileService.delete(request,fileId);
        }
        return ReturnResult.ok();
    }

    /**
     * ftp上传图片
     *
     * @param type      图片类型：身份证,营业执照,门店照等
     * @param oriName   图片原始名称
     * @param oriSuffix 图片文件后缀
     * @param oriSize   图片文件大小,单位b
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/{type}/uploadImg"}, method = RequestMethod.POST)
    public File uploadImg(@PathVariable("type") String type, String oriName,
                          String oriSuffix, int oriSize, HttpServletRequest request) {
        // 文件类型
        String filType = "";
        // 文件类型名称
        String filTypeName = "";
        // 文件类型路径
        String typePath = "";
        switch (type) {
            case FileConstants.CORP_IMG:
                filType = FileConstants.CORP_IMG;
                filTypeName = FileConstants.CORP_IMG_NAME;
                typePath = FileConstants.CORP_IMG_PATH;
                break;
            case FileConstants.BUSINESS_IMG:
                filType = FileConstants.BUSINESS_IMG;
                filTypeName = FileConstants.BUSINESS_IMG_NAME;
                typePath = FileConstants.BUSINESS_IMG_PATH;
                break;
            case FileConstants.TAX_REG_CERTIF_IMG:
                filType = FileConstants.TAX_REG_CERTIF_IMG;
                filTypeName = FileConstants.TAX_REG_CERTIF_IMG_NAME;
                typePath = FileConstants.TAX_REG_CERTIF_PATH;
                break;
            case FileConstants.ORG_IMG:
                filType = FileConstants.ORG_IMG;
                filTypeName = FileConstants.ORG_IMG_NAME;
                typePath = FileConstants.ORG_IMG_PATH;
                break;
            case FileConstants.AGREEMENT_IMG:
                filType = FileConstants.AGREEMENT_IMG;
                filTypeName = FileConstants.AGREEMENT_IMG_NAME;
                typePath = FileConstants.AGREEMENT_IMG_PATH;
                break;
            case FileConstants.LOGO_IMG:
                filType = FileConstants.LOGO_IMG;
                filTypeName = FileConstants.LOGO_IMG_NAME;
                typePath = FileConstants.LOGO_IMG_PATH;
                break;
            case FileConstants.FEEDBACK_IMG:
                filType = FileConstants.FEEDBACK_IMG;
                filTypeName = FileConstants.FEEDBACK_NAME;
                typePath = FileConstants.FEEDBACK_PATH;
                break;
            case FileConstants.IDENTITY_CARD_IMG:
                filType = FileConstants.IDENTITY_CARD_IMG;
                filTypeName = FileConstants.IDENTITY_CARD_NAME;
                typePath = FileConstants.IDENTITY_CARD_PATH;
                break;
            case FileConstants.BANK_CARD_IMG:
                filType = FileConstants.BANK_CARD_IMG;
                filTypeName = FileConstants.BANK_CARD_NAME;
                typePath = FileConstants.BANK_CARD_PATH;
                break;
            case FileConstants.STORE_IMG:
                filType = FileConstants.STORE_IMG;
                filTypeName = FileConstants.STORE_NAME;
                typePath = FileConstants.STORE_PATH;
                break;
            case FileConstants.GOODS_IMG:
                filType = FileConstants.GOODS_IMG;
                filTypeName = FileConstants.GOODS_NAME;
                typePath = FileConstants.GOODS_PATH;
                break;
            default:
                throw new BusinessException("文件类型不正确");
        }

        try {
            String data = request.getParameter("base64");
            BASE64Decoder decoder = new BASE64Decoder();
            data = data.substring(data.indexOf(",") + 1);
            // Base64解码
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }

            InputStream inputStream = new ByteArrayInputStream(b);
            int size = inputStream.available();
            File file = fileService.uploadImg(filType, filTypeName, typePath, oriName, oriSuffix, oriSize, size);
            ftpImageTask.execute(inputStream, file.getFilSerPath());
            Map<String, Object> map = new HashMap<>();
            map.put("imgFile", file);

            return file;

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("上传失败，请重试");
        }
    }

    /**
     *
     */
    @ResponseBody
    @RequestMapping("/insertImgList")
    public String insertImgList(String filelist) {
        List<File> fileList = JSON.parseArray(filelist, File.class);
        fileService.inserts(fileList);
        return Constants.DEFAULT_MSG_SUCCESS;
    }

    /**
     * 根据文件类型和外键id查询文件集合
     *
     * @param filType
     * @param foreignId
     * @return
     * @author zouwenjun
     * @date 2017年4月12日 上午10:52:59
     */
    @ResponseBody
    @RequestMapping("/selectFilesByForeignIdAndType")
    public List<File> selectFilesByForeignIdAndType(String filType, Long foreignId) {
        if (foreignId == null || foreignId == 0L) {
            return new ArrayList<File>();
        }
        return fileService.select(filType, foreignId);
    }

}
